import {
  constantRoutes
} from '@/router'
import {
  getRouters
} from '@/api/menu'
import Layout from '@/layout/index'
import ParentView from '@/components/ParentView';

const permission = {
  state: {
    routes: [],
    addRoutes: []
  },
  mutations: {
    SET_ROUTES: (state, routes) => {
      let url = ''
      if (routes.length == 1 && routes[0].path == "*"){
        url = '/user/profile'
      }else {
        if (routes[0].path != '/') {
          url = routes[0].path
        }
        if (routes[0].children.length) {
          url = url + (url ? '/' : '') + routes[0].children[0].path
        }
      }
      routes.push({
        path: '',
        component: Layout,
        redirect: url,
        hidden: true,
      })
      routes.push({
        path: '/index',
        component: Layout,
        redirect: url,
        hidden: true,
      })
      setTimeout(() => {
        state.addRoutes = routes
        state.routes = constantRoutes.concat(routes)
      }, 100)
    }
  },
  actions: {
    // 生成路由
    GenerateRoutes({
      commit
    }) {
      return new Promise(resolve => {
        // 向后端请求路由数据
        getRouters().then(res => {
          /**
           * 为smartbi的路由添加参数
           *  暂时屏蔽，后端已经做了处理
           */
          if (false && localStorage.getItem('smartUser') && localStorage.getItem('smartToken')) {
            let router = findRouter(res.data, "/smartbi/vision/index.jsp");
            if (router) {
              router.path = router.path + '?user=' + localStorage.getItem('smartUser') + '&password=' +
                localStorage.getItem('smartToken')
            }
          }

          const accessedRoutes = filterAsyncRouter(res.data)
          accessedRoutes.push({
            path: '*',
            redirect: '/404',
            hidden: true
          })
          commit('SET_ROUTES', accessedRoutes)
          resolve(accessedRoutes)
        })
      })
    }
  }
}

/**
 * 查找指定路由，以路径模糊匹配
 * @param key
 */
function findRouter(routers, key) {
  var patt1 = new RegExp("/smartbi/vision/index.jsp");
  for (let i in routers) {
    let r;
    if (patt1.test(routers[i].path)) { //匹配自身
      r = routers[i];
    } else if (routers[i].children) { //匹配下级
      r = findRouter(routers[i].children, key);
    }
    if (r) { //匹配到则返回
      return r;
    }
  }
  return null;
}

// 遍历后台传来的路由字符串，转换为组件对象
function filterAsyncRouter(asyncRouterMap) {
  return asyncRouterMap.filter(route => {
    if (route.component) {
      // Layout ParentView 组件特殊处理
      if (route.component === 'Layout') {
        route.component = Layout
      } else if (route.component === 'ParentView') {
        route.component = ParentView
      } else {
        route.component = loadView(route.component)
      }
    }
    if (route.children != null && route.children && route.children.length) {
      route.children = filterAsyncRouter(route.children)
    }
    return true
  })
}

export const loadView = (view) => { // 路由懒加载
  return (resolve) => require([`@/views/${view}`], resolve)
}

export default permission
